<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type='primary' @click="showAddUserInfo">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data='rolelist' border stripe>
        <el-table-column type='expand'>
          <template slot-scope="scope">
            <el-row :key='item1.id' v-for='(item1,i1) in scope.row.children'
              :class="['bdbutton',i1===0?'bdtop':'','vcenter']">
              <!-- 渲染一级权限 -->
              <el-col :span='5'>
                <el-tag @close='removeRightById(scope.row,item1.id)' closable>
                  {{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span='19'>
                <!-- 二级 -->
                <el-row :class="[i2===0? '':'bdtop','vcenter']" :key='item2.id'
                  v-for='(item2,i2) in item1.children'>
                  <el-col :span='6'>
                    <el-tag @close='removeRightById(scope.row,item2.id)'
                      closable type='success'>{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span='18'>
                    <el-tag type='warning' :key='item3.id'
                      v-for='item3 in item2.children' closable
                      @close='removeRightById(scope.row,item3.id)'>
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type='index'></el-table-column>
        <el-table-column label='角色名称' prop='roleName'> </el-table-column>
        <el-table-column label='角色描述' prop='roleDesc'></el-table-column>
        <el-table-column label='操作' width='300px'>
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button size='mini' type='primary'
              @click="showeditUserInfo(scope.row.id)">编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button size='mini' type='danger'
              @click="removeRolesById(scope.row.id)">删除
            </el-button>
            <!-- 分配 -->
            <el-button size='mini' type='warning'
              @click="showSetRightDialog(scope.row)">
              分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="30%"
      @close='setRightDialogClosed'>
      <el-tree :data='rightslist' :props='treeProps' show-checkbox node-key='id'
        default-expand-all :default-checked-keys='defKeys' ref='treeRef'>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRightDialogVisible" width="30%">
      <el-form ref="adduserinfoRef" :model="userInfoObj" label-width="80px"
        :rules='addUserInfoRules'>
        <el-form-item label="角色名称" prop='roleName'>
          <el-input v-model="userInfoObj.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop='roleDesc'>
          <el-input v-model="userInfoObj.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo">确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 编辑绝色的对话框 -->
    <el-dialog title="提示" :visible.sync="editDialogVisible" width="30%">
      <el-form ref="edituserinfoRef" :model="editInfo" label-width="80px"
        :rules='addUserInfoRules'>
        <el-form-item label="角色名称" prop='roleName'>
          <el-input v-model="editInfo.roleName"> </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop='roleDesc'>
          <el-input v-model="editInfo.roleDesc"> </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

export default {
  data () {
    return {
      // 所有角色列表数据
      rolelist: [],
      // 控制配置权限对话框的隐藏与显示
      setRightDialogVisible: false,
      // 添加角色的对话框
      addRightDialogVisible: false,
      // 编辑角色的对话框
      editDialogVisible: false,
      // 添加角色的数据验证规则
      addUserInfoRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 所有权限的数据
      rightslist: [],
      // 添加角色 的数组
      userInfoObj: {
        roleName: '',
        roleDese: ''
      },
      // 编辑角色的对象
      editInfo: {
        roleName: '',
        roleDese: ''
      },
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点 数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表数据
    async getRolesList () {
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色数据失败')
      this.rolelist = res.data
    },
    // 点击删除权限
    async removeRightById (role, rightid) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      if (confirmResult === 'confirm') {
        const res = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败')
        this.$message.success('删除权限成功')
        role.children = res.data
      }
    },
    // 分配角色权限按钮
    async showSetRightDialog (role) {
      this.roleId = role.id
      const res = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightslist = res.data
      // 递归获取三级权限的id
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式 获取角色下所有的三级权限的id, 并保存到数组中
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含 children 属性 , 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 点击确定为角色添加权限
    async allotRight () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const res = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('更新权限失败')
      this.$message.success('更新权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    // 点击显示添加角色框
    showAddUserInfo () {
      this.addRightDialogVisible = true
    },
    // 点击添加角色
    addUserInfo () {
      this.$refs.adduserinfoRef.validate(async v => {
        if (!v) return
        const res = await this.$http.post('roles', this.userInfoObj)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加角色成功')
        this.getRolesList()
        this.addRightDialogVisible = false
        this.userInfoObj = {}
      })
    },
    // 删除角色
    async removeRolesById (id) {
      // 弹框询问是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除 则返回一个字符串  confirm
      // 如果用户取消删除 则返回一个字符串    cancel
      // 取消删除操作
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      // 删除操作
      if (confirmResult === 'confirm') {
        const res = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除角色失败')
        this.$message.success('删除角色成功')
        this.getRolesList()
      }
    },
    // 编辑角色弹出框
    async showeditUserInfo (id) {
      const res = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败')
      this.editInfo = res.data
      this.editDialogVisible = true
    },
    // 编辑角色
    editUserInfo () {
      this.$refs.edituserinfoRef.validate(async v => {
        if (!v) return
        const res = await this.$http.put('roles/' + this.editInfo.roleId, { roleName: this.editInfo.roleName, roleDesc: this.editInfo.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('修改角色信息失败')
        this.$message.success('修改角色信息成功')
        this.getRolesList()
        this.editDialogVisible = false
      })
    }
  }
}
</script>
 <style lang="less" scoped>
.el-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbutton {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
